function [accessPaths, aerPlotPaths, dopplerPlotPaths, latencyPlotPaths, satOrbitData] = Satellite(tleFile, groundStations, outputDir)
% setupSatelliteScenario - 设置卫星场景并加载TLE与地面站数据
% 输入：
%   tleFile         - 字符串，TLE文件路径
%   groundStations  - Cell数组，每个元素是包含以下字段的结构体：
%                     latitude, longitude, minElevationAngle, name
accessPaths = {};
    aerPlotPaths = {};
    dopplerPlotPaths = {};
    latencyPlotPaths = {};
    % 设置仿真时间
    startTime = datetime(2024,1,7,14,5,0);
    stopTime = startTime + hours(6);
    sampleTime = 30; % seconds

    % 创建仿真场景
    sc = satelliteScenario(startTime, stopTime, sampleTime);

    % 导入星历数据
    sat = satellite(sc, tleFile);
    numSatellites = length(sat);
    % 设置卫星颜色
    fprintf('共加载 %d 颗卫星\n', numSatellites);

% 动态划分三组索引
groupSize = ceil(numSatellites / 3);  % 每组最大数量（前两组可能比第三组少）
idxGroup1 = 1 : groupSize;
idxGroup2 = (groupSize + 1) : min(2 * groupSize, numSatellites);
idxGroup3 = (2 * groupSize + 1) : numSatellites;

% 设置卫星颜色
if ~isempty(idxGroup1)
    set(sat(idxGroup1), 'MarkerColor', '#FF6929');  % 第一组颜色
end
if ~isempty(idxGroup2)
    set(sat(idxGroup2), 'MarkerColor', '#139FFF');  % 第二组颜色
end
if ~isempty(idxGroup3)
    set(sat(idxGroup3), 'MarkerColor', '#64D413');  % 第三组颜色
end

% 获取轨道对象
orbits = [sat(:).Orbit];

% 设置轨道颜色
if ~isempty(idxGroup1)
    set(orbits(idxGroup1), 'LineColor', '#FF6929');
end
if ~isempty(idxGroup2)
    set(orbits(idxGroup2), 'LineColor', '#139FFF');
end
if ~isempty(idxGroup3)
    set(orbits(idxGroup3), 'LineColor', '#64D413');
end

fprintf('卫星加载完毕\n');
satOrbitData = struct('ID', {}, 'Name', {}, 'Color', {}, ...
                      'OrbitX', {}, 'OrbitY', {}, 'OrbitZ', {});
for i = 1:numSatellites
    orbitStates = states(sat(i), 'CoordinateFrame', 'J2000');
    pos = orbitStates.Position;

    if any(i <= groupSize)
        color = '#FF6929';
    elseif any(i <= 2*groupSize)
        color = '#139FFF';
    else
        color = '#64D413';
    end

    satOrbitData(i).ID = sat(i).ID;
    satOrbitData(i).Name = sat(i).Name;
    satOrbitData(i).Color = color;
    satOrbitData(i).OrbitX = pos(:,1)';
    satOrbitData(i).OrbitY = pos(:,2)';
    satOrbitData(i).OrbitZ = pos(:,3)';
end
    % 创建探测器
names = sat.Name + " Camera";
cam = conicalSensor(sat,"Name",names,"MaxViewAngle",90);
    fprintf('探测器加载完毕\n');

    % 创建多个地面站
    gsList = [];
    %接入报告
% 接入报告目录
accessReportFolder = fullfile(outputDir, 'access_reports');
if ~exist(accessReportFolder, 'dir')
    mkdir(accessReportFolder);
end


% 设置输出图像目录
% AER 图像目录
aerPlotFolder = fullfile(outputDir, 'aer_plots');
if ~exist(aerPlotFolder, 'dir')
    mkdir(aerPlotFolder);
end
    for i = 1:length(groundStations)
        gsStruct = groundStations{i};
        gs = groundStation(sc, ...
            gsStruct.latitude, ...
            gsStruct.longitude, ...
            'MinElevationAngle', gsStruct.minElevationAngle, ...
            'Name', gsStruct.name);
        gs.MarkerColor = 'red';
        gs.ShowLabel = true;
        gs.LabelFontSize = 11;
        gsList{end+1} = gs;
        % 创建接入关系：access(gs, sat)
    accessObj = access(gs, sat);
    set(accessObj, LineWidth="1");
set(accessObj(idxGroup1), LineColor="#FF6929");
set(accessObj(idxGroup2), LineColor="#139FFF");
set(accessObj(idxGroup3), LineColor="#64D413");

    % 动态生成变量名，如：accessUS、accessDE、accessIN
    baseName = gsStruct.name;  % 假设 name 是 'US'、'DE'、'IN' 等
    accessVarName = ['access', baseName];  % 如 accessUS
    %查看接入报告
intervals = accessIntervals(accessObj);
if height(intervals) > 0
        % 排序
        intervalsSorted = sortrows(intervals, "StartTime", "ascend");

        % 构造文件名
        fileNameCSV = fullfile(accessReportFolder, ['access_report_', baseName, '.csv']);

        % 保存为 CSV 文件
        writetable(intervalsSorted, fileNameCSV, 'WriteRowNames', false);
        fprintf('已保存 %s 地面站的接入报告至: %s\n', baseName, fileNameCSV);
        accessPaths{end+1} = fileNameCSV;

    else
        fprintf('%s 地面站无有效接入记录。\n', baseName);
    end
    %查看AER报告
timeVector = startTime:seconds(sampleTime):stopTime;
[azimuth,elevation,range] = aer(sat(4),gs);
aer_table = table(timeVector', azimuth', elevation', range', ...
    'VariableNames', {'Time', 'Azimuth', 'Elevation', 'Range'});
%可视化AER

aerPlotPath = plotAER(aer_table,baseName, sat(4).ID, aerPlotFolder)
aerPlotPaths{end+1} = aerPlotPath;

% 多普勒频移图像目录
dopplerPlotFolder = fullfile(outputDir, 'doppler_plots');
if ~exist(dopplerPlotFolder, 'dir')
    mkdir(dopplerPlotFolder);
end

% 时延图像目录
latencyPlotFolder = fullfile(outputDir, 'latency_plots');
if ~exist(latencyPlotFolder, 'dir')
    mkdir(latencyPlotFolder);
end

%计算时延
[a,b,latencyPlotPath]=cal_latency(sat(5),gs,30,2,latencyPlotFolder);
latencyPlotPaths{end+1} = latencyPlotPath;
%计算多普勒频移
[fShift,time,dopplerInfo,dopplerPlotPath] = cal_doppler(sat(5),gs,5e9,2,dopplerPlotFolder);
dopplerPlotPaths{end+1} = dopplerPlotPath;
end

    % 可视化地面站位置
    figure;
    % 提取所有地面站的纬度和经度
lat = zeros(size(gsList));
lon = zeros(size(gsList));
for i = 1:length(gsList)
    lat(i) = gsList{i}.Latitude;
    lon(i) = gsList{i}.Longitude;
end

    geoscatter(lat, lon, 'filled', 'MarkerFaceColor', 'r');
    geolimits([-75 75], [-180 180]);
    title('Ground Stations');
    fprintf('地面站加载完毕\n');
v = satelliteScenarioViewer(sc,"ShowDetails",false);
show(sat.Orbit);
fprintf('场景设置完毕\n')
fov = fieldOfView(cam([cam.Name] == "Satellite 4 Camera"));
fprintf('卫星选择完毕\n')

    play(sc);
end